using Prism.Mvvm;
using Prism.Commands;
using System.Windows;
using CPlatePrintSys.Application.Services;
using System.Linq;
using System;

namespace CPlatePrintSys.Win.ViewModels
{
    public class AddMotherShipViewModel : BindableBase
    {
        private readonly IShipConfigService _service;
        public string MotherShipNo { get; set; }
        public DelegateCommand SaveCommand { get; }
        public DelegateCommand CancelCommand { get; }

        public AddMotherShipViewModel(IShipConfigService service)
        {
            _service = service;
            SaveCommand = new DelegateCommand(OnSave);
            CancelCommand = new DelegateCommand(OnCancel);
        }

        private async void OnSave()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(MotherShipNo))
                {
                    MessageBox.Show("请输入母船船号！");
                    return;
                }
                await _service.AddMotherShipAsync(MotherShipNo.Trim().ToUpper());
            }
            catch(Exception ex)
            {
                MessageBox.Show($"添加母船失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {

                CloseDialog(true);
            }

        }

        private void OnCancel() => CloseDialog(false);

        private void CloseDialog(bool? result)
        {
            // Fix: Ensure Application.Current is properly referenced
            var window = System.Windows.Application.Current.Windows.OfType<Window>().FirstOrDefault(w => w.DataContext == this);
            if (window != null)
                window.DialogResult = result;
        }
    }
} 